package xs.szw.service.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import xs.szw.common.result.ResultCode;
import xs.szw.common.utils.ResponseUtils;
import xs.szw.service.utils.SecurityUtils;

import java.io.IOException;

/**
 * @program: My_SpringSecurity
 * @description: 授权异常处理  springSecurity授权失败处理(只有在配置类中配置的接口才会触发这个，如果是注释的只会被全局异常捕获) ->.requestMatchers("").hasAuthority("")
 * @author: Songzw
 * @create: 2025-02-01 14:08
 **/
@Component
@Slf4j
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        // 打印 warn 的原因是，不定期合并 warn，看看有没恶意破坏
        log.warn("[commence][访问 URL({}) 时，用户({}) 权限不够]", request.getRequestURI(),
                SecurityUtils.getLoginUserId(), accessDeniedException);
//        Result<Object> fail = Result.fail(String.valueOf(HttpStatus.FORBIDDEN.value()), "没有权限访问！");
//        ServletUtils.renderString(response, JSON.toJSONString(fail),HttpStatus.FORBIDDEN.value());
        ResponseUtils.writeErrMsg(response, ResultCode.ACCESS_DENIED);
    }
}
